package JVM工作区.优化案例;

import java.util.HashSet;

/**
 * 模拟死锁案例
 * @ClassName: jvmUpdate01
 * @Author: AllenSun
 * @Date: 2022/11/8 下午8:51
 */
public class jvmUpdate02 {

    private static HashSet hashSet = new HashSet();

    public static void main(String[] args) {
        //模拟死锁
        deadThread();
        //创建对象
        addHashSetThread();
        //模拟高CPU
        cpuHigh();
    }

    /** 模拟死锁
     * @MethodName: deadThread
     * @Author: AllenSun
     * @Date: 2022/11/9 上午12:59
     */
    private static void deadThread() {
        Object lock1 = new Object();
        Object lock2 = new Object();

        new Thread(()->{
            synchronized (lock1) {
                try {
                    System.out.println("线程1启动");
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2) {
                    System.out.println("线程1结束");
                }
            }
        }).start();

        new Thread(()->{
            synchronized (lock2) {
                try {
                    System.out.println("线程2启动");
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1) {
                    System.out.println("线程2结束");
                }
            }
        }).start();

        System.out.println("主线程结束");
    }

    /**不断的向HashSet集合添加数据
     * @MethodName: addHashSetThread
     * @Author: AllenSun
     * @Date: 2022/11/9 上午1:03
     */
    public static void addHashSetThread() {
        new Thread(()->{
            int count = 0;
            while (true) {
                try {
                    hashSet.add("count"+count);
                    Thread.sleep(10000);
                    count++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    /** 模拟CPU飙升
     * @MethodName: cpuHigh
     * @Author: AllenSun
     * @Date: 2022/11/9 上午1:05
     */
    public static void cpuHigh() {
        new Thread(()->{
            while (true) {

            }
        }).start();
    }
}
